const { Sequelize, DataTypes, Model, Op } = require("sequelize");

const sequelize = new Sequelize("coderhub", "root", "", {
  host: "localhost",
  dialect: "mysql",
});

class Product extends Model {}

Product.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    title: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    price: DataTypes.DOUBLE,
    score: DataTypes.DOUBLE,
  },
  {
    tableName: "products",
    createdAt: false,
    updatedAt: false,
    sequelize,
  }
);

async function queryProduct() {
  // 查询数据库中product表中的所有内容
  const result = await Product.findAll({
    where: {
      price: {
        [Op.gte]: 5000,
      },
    },
  });
  console.log(result);

  // 插入数据
  const result = await Product.create({
    title: "三星Nova",
    price: 8888,
    score: 5.5,
  });
  console.log(result);

  // 更新数据
  const result = await Product.update(
    {
      price: 3688,
    },
    {
      where: {
        id: 1,
      },
    }
  );
  console.log(result);

  // 删除数据
  const result = await Product.destroy({
    where: {
      title: "三星Nova",
    },
  });

  console.log(result);
}

queryProduct();
